import pandas as pd
import numpy as np
import re
import os
import json

def calculate_level2_weights(file_path):
    df_level2 = pd.read_excel(file_path, sheet_name="Sheet1")
    row = df_level2.iloc[0]
    score_columns = [col for col in df_level2.columns if '——' in col]

    def str_to_float(s):
        try:
            if isinstance(s, str) and '/' in s:
                numerator, denominator = s.split('/')
                return float(numerator) / float(denominator)
            return float(s)
        except:
            return 1.0

    grouped_scores = {}
    current_group = None
    for idx, col in enumerate(score_columns):
        match = re.search(r'(\d+)\.(.+?)类参数之间的重要性对比', col)
        if match:
            current_group = match.group(2).strip()
        if current_group:
            parts = col.split('——')
            if len(parts) != 2:
                continue
            parts[0] = re.split(r'[）—]', parts[0])[-1].strip()
            param1, param2 = parts[0].strip(), parts[1].strip()
            score = str_to_float(row[col])
            grouped_scores.setdefault(current_group, []).append((param1, param2, score))

    def build_pairwise_matrix(pairs):
        items = sorted(set([i for a, b, _ in pairs for i in (a, b)]))
        n = len(items)
        matrix = np.ones((n, n))
        for a, b, val in pairs:
            i, j = items.index(a), items.index(b)
            matrix[i, j] = val
            matrix[j, i] = 1 / val
        return pd.DataFrame(matrix, index=items, columns=items)

    group_matrices = {group: build_pairwise_matrix(pairs) for group, pairs in grouped_scores.items()}

    result = {}
    for group, matrix in group_matrices.items():
        weights = matrix.sum(axis=1) / matrix.values.sum()
        result[group] = {item: round(weight, 4) for item, weight in weights.items()}

    project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    out_dir = os.path.join(project_root, "数据")
    os.makedirs(out_dir, exist_ok=True)
    out_path = os.path.join(out_dir, "二级指标权重.json")
    with open(out_path, 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    print(f"已保存权重到：{out_path}")

# 示例调用（可注释）
file_path = "/Users/lhd/Downloads/320411437_按文本_AHP（层次分析法）二级指标专家打分表_2_1.xlsx"
calculate_level2_weights(file_path)
